package cn.jinjimi.app.player.impl;

import cn.jinjimi.app.player.ErrorRetry;
import cn.jinjimi.app.player.XrkMedia;
import cn.jinjimi.app.player.XrkPlayer;
import cn.jinjimi.app.player.listener.OnBufferListener;
import cn.jinjimi.app.player.listener.OnCompletionListener;
import cn.jinjimi.app.player.listener.OnErrorListener;
import cn.jinjimi.app.player.listener.OnUpdateListener;

/**
 * Created by lforxeverc on 2017/5/15.
 */

public abstract class XrkBasePlayer<D extends XrkMedia> implements XrkPlayer<D> {
    protected OnErrorListener mErrorListener;
    protected OnCompletionListener mCompleteListener;
    protected OnUpdateListener mUpdateListener;
    protected OnBufferListener mBufferListener;
    protected ErrorRetry mErrorRetry;
    protected D mMedia;
    protected long mDuration;
    protected long mCurrentPosition;
    protected boolean isPlaying;


    public void setOnErrorListener(OnErrorListener mErrorListener) {
        this.mErrorListener = mErrorListener;
    }

    public void setOnCompleteListener(OnCompletionListener mCompleteListener) {
        this.mCompleteListener = mCompleteListener;
    }

    public void setOnUpdateListener(OnUpdateListener mUpdateListener) {
        this.mUpdateListener = mUpdateListener;
    }

    public void setOnBufferListener(OnBufferListener mBufferListener) {
        this.mBufferListener = mBufferListener;
    }

    public void setErrorRetry(ErrorRetry mErrorRetry) {
        this.mErrorRetry = mErrorRetry;
    }

    @Override
    public void setMediaData(D media) {
        setMediaData(media, true);
    }

    protected void setMediaData(D media, boolean reset) {
        mMedia = media;
        if (mErrorRetry != null && reset)
            mErrorRetry.reset();
        prepare(mMedia);
    }

    protected void onError(Exception e) {
        isPlaying = false;
        if (mErrorRetry != null && mErrorRetry.onAutoRetryWhenError()) {
            return;
        }
        if (mErrorListener != null) {
            mErrorListener.onError(mMedia, e.getMessage());
        }
    }

    @Override
    public D getMediaData() {
        return mMedia;
    }

    public long getDuration() {
        return mDuration;
    }

    public boolean isPlaying() {
        return isPlaying;
    }

    //设置数据源后调用
    abstract void prepare(D media);

    //重试
    protected boolean retry() {
        return false;
    }

    public abstract void stopBuffering();

    public abstract void startBuffering();
}
